import { useState, useEffect } from 'react'
import { View, Text, Input, Canvas } from '@tarojs/components'
import { Button, Cell, Tabs, Dialog, Radio, Image } from '@taroify/core'
import Taro, { useShareAppMessage, useShareTimeline } from '@tarojs/taro'
import './index.scss'

// 获取当前主题
const getCurrentTheme = () => {
  try {
    const savedTheme = Taro.getStorageSync('user-theme-preference')
    if (savedTheme && (savedTheme === 'mint' || savedTheme === 'cream')) {
      return savedTheme
    }
    return 'mint' // 默认主题
  } catch (error) {
    console.error('读取主题偏好出错', error)
    return 'mint'
  }
}

const LayoffCalculator = () => {
  // 主要状态
  const [monthlySalary, setMonthlySalary] = useState('')
  const [yearsWorked, setYearsWorked] = useState('')
  const [monthsWorked, setMonthsWorked] = useState('')
  const [compensationMultiplier, setCompensationMultiplier] = useState('N')
  const [customMultiplierFactor, setCustomMultiplierFactor] = useState('')
  const [customMultiplierExtra, setCustomMultiplierExtra] = useState('')
  const [localAverageSalary] = useState(8000) // 当地平均工资示例值
  const [result, setResult] = useState(null)
  const [showCustomMultiplierDialog, setShowCustomMultiplierDialog] = useState(false)
  const [shareDialogVisible, setShareDialogVisible] = useState(false)
  const codeImg = 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/mini-code.png'
  const [canvasRef, setCanvasRef] = useState(null)
  // 添加主题状态
  const [currentTheme, setCurrentTheme] = useState('mint')

  // 监听主题变化
  useEffect(() => {
    const theme = getCurrentTheme()
    setCurrentTheme(theme)

    // 监听主题变化事件
    const updateTheme = () => {
      const newTheme = getCurrentTheme()
      setCurrentTheme(newTheme)
    }

    // 每5秒检查一次主题是否变化
    const interval = setInterval(updateTheme, 5000)

    return () => clearInterval(interval)
  }, [])

  // 自定义表达式计算方法 - 简化为基本公式结构
  const calculateCustomMultiplier = (n) => {
    const factor = parseFloat(customMultiplierFactor) || 0
    const extra = parseFloat(customMultiplierExtra) || 0
    return factor * n + extra
  }

  // 根据赔偿金额获取幽默提示
  const getHumorousTip = (amount) => {
    if (amount < 5000) {
      return '这点小钱，够买顿网红奶茶，吃个痛快！'
    } else if (amount < 50000) {
      return '刚好补贴一下假期旅游基金，旅个小假吧~'
    } else if (amount < 100000) {
      return '恭喜你，一笔小小意外之财，财富自由还差点！'
    } else if (amount < 500000) {
      return '幸运之神眷顾，轻松迈入土豪行列！'
    } else if (amount < 1000000) {
      return '可以来一场说走就走的环球旅行了！'
    } else {
      return '恭喜您，已达到人生巅峰，请安排人生下一个目标！'
    }
  }

  // 获取分享卡片背景色
  const getShareCardColor = (amount) => {
    if (amount < 5000) {
      return 'grey'
    } else if (amount < 50000) {
      return 'blue'
    } else {
      return 'gold'
    }
  }

  // 赔偿计算函数
  const calculateCompensation = () => {
    if (!monthlySalary || !(yearsWorked || monthsWorked)) {
      Taro.showToast({
        title: '请输入月薪和工龄',
        icon: 'none',
        duration: 2000
      })
      return
    }

    // 1. 计算服务年限N
    const years = Number(yearsWorked) || 0
    const months = Number(monthsWorked) || 0
    let serviceYears

    if (months >= 6) {
      serviceYears = years + 1
    } else if (months > 0) {
      serviceYears = years + 0.5
    } else {
      serviceYears = years
    }

    // 服务年限最高不超过12年
    const cappedServiceYears = Math.min(serviceYears, 12)

    // 2. 确定月薪基数
    let salary = Number(monthlySalary)
    const maxSalaryBase = localAverageSalary * 3

    // 如果超过当地平均工资3倍，则按3倍计算
    if (salary > maxSalaryBase) {
      salary = maxSalaryBase
    }

    // 3. 计算赔偿倍数
    let multiplier

    switch (compensationMultiplier) {
      case 'N':
        multiplier = cappedServiceYears
        break
      case 'N+1':
        multiplier = cappedServiceYears + 1
        break
      case 'N+2':
        multiplier = cappedServiceYears + 2
        break
      case '2N':
        multiplier = cappedServiceYears * 2
        break
      case 'custom':
        multiplier = calculateCustomMultiplier(cappedServiceYears)
        break
      default:
        multiplier = cappedServiceYears
    }

    // 4. 计算最终赔偿金额
    const compensationAmount = salary * multiplier

    // 设置结果
    setResult({
      amount: compensationAmount,
      serviceYears,
      cappedServiceYears,
      salaryBase: salary,
      multiplier,
      humorousTip: getHumorousTip(compensationAmount),
      shareCardColor: getShareCardColor(compensationAmount)
    })
  }

  // 复制分享文案到剪贴板
  const copyShareText = () => {
    if (result) {
      let formulaDisplay = compensationMultiplier
      if (compensationMultiplier === 'custom') {
        formulaDisplay = formatCustomFormula()
      }

      const shareText = `我刚算到因 ${formulaDisplay} 赔偿了 ${result.amount.toFixed(
        2
      )} 元，财富自由近在眼前，谁来请我喝杯咖啡？`

      Taro.setClipboardData({
        data: shareText,
        success: function () {
          Taro.showToast({
            title: '文案已复制',
            icon: 'success',
            duration: 2000
          })
        }
      })
    }
  }

  // 保存分享图片到手机
  const saveShareImage = () => {
    if (!canvasRef) return

    Taro.showLoading({
      title: '正在生成图片...'
    })

    setTimeout(() => {
      try {
        const ctx = Taro.createCanvasContext('shareCanvas')

        // 设置背景颜色（基于结果卡片颜色）
        let bgGradient = '#ffffff'
        if (result.shareCardColor === 'grey') {
          bgGradient = '#424242'
        } else if (result.shareCardColor === 'blue') {
          bgGradient = '#1565c0'
        } else if (result.shareCardColor === 'gold') {
          bgGradient = '#ff9800'
        }

        // 绘制背景
        ctx.fillStyle = bgGradient
        ctx.fillRect(0, 0, 300, 450)

        // 绘制标题
        ctx.fillStyle = '#ffffff'
        ctx.font = 'bold 18px sans-serif'
        ctx.textAlign = 'center'
        ctx.fillText('赔你一个好心情', 150, 40)

        // 绘制金额
        ctx.font = 'bold 24px sans-serif'
        ctx.fillText(`¥ ${result.amount.toFixed(2)}`, 150, 80)

        // 绘制详情
        ctx.font = '14px sans-serif'
        ctx.textAlign = 'center'
        ctx.fillText(`月薪: ${monthlySalary} 元`, 150, 120)
        ctx.fillText(`工龄: ${yearsWorked || 0}年${monthsWorked || 0}月`, 150, 145)
        ctx.fillText(`赔偿规则: ${compensationMultiplier}`, 150, 170)

        // 绘制幽默提示 - 不再添加背景色
        ctx.textAlign = 'center'
        ctx.fillStyle = '#ffffff'
        ctx.font = 'italic 14px sans-serif'
        ctx.fillText(result.humorousTip, 150, 210, 240)

        // 先加载二维码图片，然后绘制
        Taro.getImageInfo({
          src: codeImg,
          success: (imgRes) => {
            // 绘制二维码
            ctx.drawImage(imgRes.path, 100, 260, 100, 100)

            // 绘制提示文字
            ctx.fillStyle = '#ffffff'
            ctx.font = '12px sans-serif'
            ctx.textAlign = 'center'
            ctx.fillText('长按识别小程序码计算你的补偿金', 150, 380)

            // 绘制完成后导出图片并保存
            ctx.draw(false, () => {
              setTimeout(() => {
                // 在确保绘制完成后导出为图片
                Taro.canvasToTempFilePath({
                  canvasId: 'shareCanvas',
                  success: (res) => {
                    Taro.hideLoading()

                    // 保存到相册
                    Taro.saveImageToPhotosAlbum({
                      filePath: res.tempFilePath,
                      success: () => {
                        Taro.showToast({
                          title: '保存成功',
                          icon: 'success',
                          duration: 2000
                        })
                      },
                      fail: (err) => {
                        console.error('保存失败', err)
                        // 检查是否是因为权限问题
                        if (err.errMsg.indexOf('auth deny') >= 0) {
                          Taro.showModal({
                            title: '保存失败',
                            content: '请允许小程序访问相册权限后重试',
                            showCancel: false
                          })
                        } else {
                          Taro.showToast({
                            title: '保存失败，请重试',
                            icon: 'none',
                            duration: 2000
                          })
                        }
                      }
                    })
                  },
                  fail: (err) => {
                    console.error('生成图片失败', err)
                    Taro.hideLoading()
                    Taro.showToast({
                      title: '生成图片失败',
                      icon: 'none',
                      duration: 2000
                    })
                  }
                })
              }, 300) // 确保canvas绘制完成
            })
          },
          fail: (err) => {
            console.error('加载图片失败', err)
            Taro.hideLoading()
            Taro.showToast({
              title: '加载图片失败',
              icon: 'none',
              duration: 2000
            })
          }
        })
      } catch (error) {
        console.error('Canvas绘制错误', error)
        Taro.hideLoading()
        Taro.showToast({
          title: '生成图片失败',
          icon: 'none',
          duration: 2000
        })
      }
    }, 100)
  }

  // 选择赔偿倍数
  const selectMultiplier = (value) => {
    setCompensationMultiplier(value)
    if (value === 'custom') {
      setShowCustomMultiplierDialog(true)
    }
  }

  // 确认自定义倍数
  const confirmCustomMultiplier = () => {
    if (!customMultiplierFactor) {
      Taro.showToast({
        title: '请输入乘数系数',
        icon: 'none',
        duration: 2000
      })
      return
    }
    setShowCustomMultiplierDialog(false)
  }

  // 用于格式化显示自定义公式的辅助函数
  const formatCustomFormula = () => {
    const factor = customMultiplierFactor || '0'
    const extra = customMultiplierExtra || '0'

    if (factor === '0' && extra === '0') {
      return '点击编辑'
    }

    if (factor === '0') {
      return extra
    }

    return extra === '0' ? `${factor}N` : `${factor}N+${extra}`
  }

  // 分享给朋友
  useShareAppMessage(() => {
    return {
      title: '被约谈前夜，我偷偷算好了这笔账...（附合法补偿公式）',
      path: '/pages-layoff/index',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-money.jpg'
    }
  })

  // 分享到朋友圈
  useShareTimeline(() => {
    return {
      title: '一键计算你的补偿金，N+1? 2N? 算完才知道值多少钱！',
      query: '',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-money.jpg'
    }
  })

  return (
    <View className={`layoff-calculator-page theme-${currentTheme}`}>
      <View className='header'>
        <Text className='title'>裁员补偿计算器</Text>
      </View>

      <View className='input-section'>
        <Cell.Group inset>
          <View className='custom-field'>
            <Text className='field-title'>月薪 (元)</Text>
            <Input
              className='field-input'
              type='digit'
              value={monthlySalary}
              placeholder='输入月薪金额'
              onInput={(e) => setMonthlySalary(e.detail.value)}
            />
          </View>

          <View className='service-time-container'>
            <View className='custom-field'>
              <Text className='field-title'>工龄 (年)</Text>
              <Input
                className='field-input'
                type='digit'
                value={yearsWorked}
                placeholder='年'
                onInput={(e) => setYearsWorked(e.detail.value)}
              />
            </View>
            <View className='custom-field'>
              <Text className='field-title'>工龄 (月)</Text>
              <Input
                className='field-input'
                type='digit'
                value={monthsWorked}
                placeholder='月'
                onInput={(e) => {
                  const value = e.detail.value
                  const numValue = parseInt(value, 10)

                  // 检查是否超过12个月
                  if (numValue && numValue > 12) {
                    Taro.showToast({
                      title: '月份已限制为12个月',
                      icon: 'none',
                      duration: 2000
                    })
                    setMonthsWorked('12')
                  } else {
                    setMonthsWorked(value)
                  }
                }}
              />
            </View>
          </View>

          <Cell title='赔偿倍数：'></Cell>
          <View className='cell-box'>
            <Radio.Group
              value={compensationMultiplier}
              direction='horizontal'
              onChange={(value) => selectMultiplier(value)}>
              <Radio name='N'>N</Radio>
              <Radio name='N+1'>N+1</Radio>
              <Radio name='N+2'>N+2</Radio>
              <Radio name='2N'>2N</Radio>
              <Radio name='custom'>自定义</Radio>
            </Radio.Group>
          </View>

          {compensationMultiplier === 'custom' && (
            <Cell title='自定义公式'>
              <View className='custom-formula-box'>
                <Text className='custom-formula'>{formatCustomFormula()}</Text>
                <Button size='small' onClick={() => setShowCustomMultiplierDialog(true)}>
                  编辑
                </Button>
              </View>
            </Cell>
          )}
        </Cell.Group>
      </View>

      <View className='action-buttons'>
        <Button className='calculate-btn' onClick={calculateCompensation}>
          计算补偿金额
        </Button>
      </View>

      {result && (
        <View className='result-section'>
          <View className='result-card' style={{ backgroundColor: result.shareCardColor }}>
            <Text className='result-amount'>¥ {result.amount.toFixed(2)}</Text>
            <Text className='result-title'>应得赔偿金额</Text>

            <View className='result-details'>
              <Text>按劳动合同法第47条，服务年限 {result.serviceYears} 年</Text>
              {result.serviceYears !== result.cappedServiceYears && <Text>(受限于最高12年补偿限制)</Text>}
              <Text>赔偿基数: {result.salaryBase.toFixed(2)} 元</Text>
              <Text>
                赔偿倍数: {compensationMultiplier}{' '}
                {compensationMultiplier === 'custom' ? `(${formatCustomFormula()})` : ''}
              </Text>
            </View>

            <View className='humor-tip'>
              <Text>{result.humorousTip}</Text>
            </View>

            <View className='share-actions'>
              <Button className='share-btn' onClick={() => setShareDialogVisible(true)}>
                生成分享卡片
              </Button>
              <Button className='copy-btn' onClick={copyShareText}>
                复制分享文案
              </Button>
            </View>
          </View>

          <View className='tips-section'>
            <Tabs>
              <Tabs.TabPane title='基数核对'>
                <View className='tip-content'>
                  <Text>赔偿基数包含&quot;计时/计件工资、奖金、津贴和补贴&quot;等全额货币收入</Text>
                  <Text>若近12个月平均工资低于当地最低工资，则按最低工资标准计发</Text>
                </View>
              </Tabs.TabPane>
              <Tabs.TabPane title='上限说明'>
                <View className='tip-content'>
                  <Text>单月基数最高为当地职工月平均工资3倍，且补偿年限封顶12年</Text>
                </View>
              </Tabs.TabPane>
              <Tabs.TabPane title='特殊情况'>
                <View className='tip-content'>
                  <Text>代通知金：若公司未提前30日书面通知员工，则需额外支付1个月工资作为代通知金</Text>
                  <Text>违法解除：可启用双倍2N赔偿</Text>
                  <Text>经济性裁员/破产重整：可协商2N或更高倍数</Text>
                </View>
              </Tabs.TabPane>
            </Tabs>
          </View>
        </View>
      )}

      {/* 自定义倍数对话框 */}
      <Dialog open={showCustomMultiplierDialog} onClose={() => setShowCustomMultiplierDialog(false)}>
        <Dialog.Header>自定义赔偿倍数公式</Dialog.Header>
        <Dialog.Content>
          <View className='formula-container'>
            <View className='formula-row'>
              <View className='custom-field small-input'>
                <Input
                  className='field-input'
                  type='digit'
                  placeholder='*N'
                  value={customMultiplierFactor}
                  onInput={(e) => setCustomMultiplierFactor(e.detail.value)}
                />
              </View>
              {/* <Text className='formula-variable'>N</Text> */}
              <Text className='formula-operator'>+</Text>
              <View className='custom-field small-input'>
                <Input
                  className='field-input'
                  type='digit'
                  placeholder='例如: 5'
                  value={customMultiplierExtra}
                  onInput={(e) => setCustomMultiplierExtra(e.detail.value)}
                />
              </View>
            </View>
          </View>
          <Text className='formula-help'>系数乘以工作年限(n)后再加上附加值</Text>
        </Dialog.Content>
        <Dialog.Actions>
          <Button onClick={() => setShowCustomMultiplierDialog(false)}>取消</Button>
          <Button onClick={confirmCustomMultiplier}>确认</Button>
        </Dialog.Actions>
      </Dialog>

      {/* 分享对话框 */}
      <Dialog open={shareDialogVisible} onClose={() => setShareDialogVisible(false)}>
        <Dialog.Header>分享卡片</Dialog.Header>
        <Dialog.Content>
          {result && (
            <View className='share-preview'>
              <View className='share-card' style={{ backgroundColor: result.shareCardColor }}>
                <Text className='share-card-title'>赔你一个好心情</Text>
                <Text className='share-card-amount'>¥ {result.amount.toFixed(2)}</Text>
                <Text className='share-card-subtitle'>恭喜你！</Text>
                <View className='share-card-details'>
                  <Text>月薪: {monthlySalary} 元</Text>
                  <Text>
                    工龄: {yearsWorked || 0}年{monthsWorked || 0}月
                  </Text>
                  <Text>赔偿规则: {compensationMultiplier}</Text>
                </View>
                <View className='humor-tip'>
                  <Text>{result.humorousTip}</Text>
                </View>
                <View className='qrcode-container'>
                  <Image src={codeImg} className='qrcode-image' />
                  <Text className='qrcode-tip'>长按识别小程序码</Text>
                </View>
              </View>

              {/* 用于生成分享图片的Canvas */}
              <Canvas
                canvasId='shareCanvas'
                style={{ width: '300px', height: '450px', position: 'absolute', left: '-9999px' }}
                className='share-canvas'
                ref={(node) => setCanvasRef(node)}
              />
            </View>
          )}
        </Dialog.Content>
        <Dialog.Actions>
          <Button onClick={() => setShareDialogVisible(false)}>关闭</Button>
          <Button onClick={copyShareText}>复制文案</Button>
          <Button onClick={saveShareImage} color='primary'>
            保存图片
          </Button>
        </Dialog.Actions>
      </Dialog>
    </View>
  )
}

export default LayoffCalculator
